package cn.crm.web.controller.business;

import cn.crm.common.annotation.Anonymous;
import cn.crm.common.annotation.Log;
import cn.crm.common.core.controller.BaseController;
import cn.crm.common.core.domain.AjaxResult;
import cn.crm.common.core.domain.entity.SysUser;
import cn.crm.common.core.page.TableDataInfo;
import cn.crm.common.enums.BusinessType;
import cn.crm.common.utils.DateUtils;
import cn.crm.common.utils.poi.ExcelUtil;
import cn.crm.system.domain.pojo.dto.BusinessDto;
import cn.crm.system.domain.pojo.dto.CaseDto;
import cn.crm.system.domain.pojo.dto.ScheduleCaseDTO;
import cn.crm.system.domain.pojo.entity.Specification;
import cn.crm.system.domain.pojo.vo.BusinessVo;
import cn.crm.system.domain.pojo.vo.CaseAndScheduleDownloadVo;
import cn.crm.system.domain.pojo.vo.CaseVo;
import cn.crm.system.domain.pojo.vo.ScheduleCaseVo;
import cn.crm.system.service.ICaseService;
import cn.crm.system.service.ISysUserService;
import cn.crm.system.service.impl.BusinessServiceImpl;
import cn.crm.system.service.impl.CaseServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/case")
@Api(tags = "业务模块/案件管理")
public class CaseController extends BaseController {

    @Autowired
    private ICaseService caseService;
    @Autowired
    private ISysUserService userService;

    public CaseController() {
        log.debug("创建控制器对象：CaseController");
    }

    @GetMapping("/list")
    @ApiOperation("查询案件进度资料")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件进度", businessType = BusinessType.OTHER)
    public TableDataInfo GetCaselist(CaseDto caseDto) {
        log.debug("开始处理查询客户资料的接口");
        startPage();
        List<CaseVo> caseVos = caseService.selectCasesList(caseDto);
        return  getDataTable(caseVos);
    }

    @PreAuthorize("@ss.hasPermi('system:case:add')")
    @PostMapping("/add")
    @ApiOperation("添加案件资料")
    @Log(title = "案件管理", businessType = BusinessType.INSERT)
    public AjaxResult  addBusiness(@RequestBody CaseDto caseDto) {
        log.debug("开始处理添加案件资料的接口");
        if (caseDto.getBusinessId() == null){
            return AjaxResult.warn("添加案件失败，添加客户未找到");
        }
        int insertcase = caseService.insertcase(caseDto);
        //添加案件成功开始添加案件的日程

        if (insertcase < 2){
            return AjaxResult.error("添加案件失败");
        }
        return AjaxResult.success("添加成功");
    }

    @GetMapping("/{id}")
    @ApiOperation("根据案件id查询资料")
    @PreAuthorize("@ss.hasPermi('system:case:query')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public AjaxResult getInfo(@PathVariable Long id){
        log.debug("开始通过id查询案件资料的接口");
        CaseVo selectcasebyid = caseService.selectcasebyid(id);
        return  success(selectcasebyid);
    }


    @GetMapping("/count")
    @ApiOperation("查询案件总数")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public  AjaxResult GetCasecount() {

        Long selectcount = caseService.selectcount();
//        return null;
        return  AjaxResult.success(selectcount);
    }



    @GetMapping("/percentage")
    @ApiOperation("查询案件每月百分比总数")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public  AjaxResult GetBusinesspercentage() {

        Long selectcount = caseService.selectpercentage();
//        return null;
        return  AjaxResult.success(selectcount);
    }

    @GetMapping("/Newadd")
    @ApiOperation("查询案件本月新增")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public  AjaxResult GetNewadd() {
        Long selectcount = caseService.Newadd();
//        return null;
        return  AjaxResult.success(selectcount);
    }

    @GetMapping("/selectsettle")
    @ApiOperation("查询总共多少结案")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public  AjaxResult selectsettle() {
        Long selectcount = caseService.selectsettle();
//        return null;
        return  AjaxResult.success(selectcount);
    }

    @GetMapping("/selectpercentage")
    @ApiOperation("查询结案案件每月百分比总数")
    @PreAuthorize("@ss.hasPermi('system:case:list')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public  AjaxResult selectpercentage() {

        Long selectcount = caseService.selectcasepercentage();
//        return null;
        return  AjaxResult.success(selectcount);
    }



    @GetMapping("/list/{businessId}")
    @ApiOperation("根据案件公司id查询资料")
    @PreAuthorize("@ss.hasPermi('system:case:query')")
    @Log(title = "案件管理", businessType = BusinessType.OTHER)
    public TableDataInfo getInfoByBusinessId(@PathVariable Long businessId){
        log.debug("开始通过id查询案件资料的接口");
        startPage();
        List<CaseVo> selectcasebybusinessId = caseService.selectcasebybusinessId(businessId);
        return  getDataTable(selectcasebybusinessId);
    }

    @Log(title = "案件管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    @ApiOperation("删除案件资料")
    @PreAuthorize("@ss.hasPermi('system:case:delete')")
    public AjaxResult delete(@PathVariable Long[] id){
        log.debug("开始删除案件资料的接口");
        int Deletecase = caseService.delcasebyid(id);
        if (Deletecase < 1){
            return AjaxResult.error("删除客户资料失败");
        }

        return AjaxResult.success("删除客户资料成功");
    }


    @Log(title = "案件管理", businessType = BusinessType.DELETE)
    @GetMapping("/selectUser")
    @ApiOperation("查询用户及其联系人手机")
    @PreAuthorize("@ss.hasPermi('system:case:add')")
    public AjaxResult GetUserspecifications() {
        log.debug("开始处理查询公开联系人及其手机");
        List<SysUser> sysUsers = userService.selectUserListAll();
        return success(sysUsers);
    }

    @Log(title = "案件管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    @ApiOperation("修改案件资料")
    @PreAuthorize("@ss.hasPermi('system:case:update')")
    public AjaxResult update( @RequestBody CaseDto caseDto){
        log.debug("开始修改客户资料的接口");
        int updatecase = caseService.updatecase(caseDto);

        if (updatecase < 1){
            return AjaxResult.error("修改客户资料失败");
        }
        return AjaxResult.success("修改客户资料成功");
    }

    @Log(title = "案件管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:case:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response,CaseDto caseDto)
    {
        List<CaseVo> caseVos = caseService.selectCasesList(caseDto);
        ExcelUtil<CaseVo> util = new ExcelUtil<CaseVo>(CaseVo.class);
        util.exportExcel(response, caseVos, "案件数据");
    }


    @Log(title = "案件管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:case:export')")
    @PostMapping("/exportSchedule")
    public void exportSchedule(HttpServletResponse response,CaseDto caseDto) {
        CaseVo caseInfo = caseService.selectcasebyid(caseDto.getBusinessId());

        CaseAndScheduleDownloadVo downloadVo = new CaseAndScheduleDownloadVo();
        BeanUtils.copyProperties(caseInfo, downloadVo);

        if (caseInfo.getScheduleCaseVos() != null && !caseInfo.getScheduleCaseVos().isEmpty()) {
            StringBuilder timeBuilder = new StringBuilder();
            StringBuilder infoBuilder = new StringBuilder();
            StringBuilder stateBuilder = new StringBuilder();

            for (int i = 0; i < caseInfo.getScheduleCaseVos().size(); i++) {
                ScheduleCaseVo scheduleCase = caseInfo.getScheduleCaseVos().get(i);

                if (i > 0) {
                    timeBuilder.append(";\n");  // 使用换行符分隔不同记录
                    infoBuilder.append(";\n");
                    stateBuilder.append(";\n");
                }

                // 直接使用String类型的scheduleTime
                timeBuilder.append(scheduleCase.getScheduleTime() != null ? scheduleCase.getScheduleTime() : "");
                infoBuilder.append(scheduleCase.getScheduleInfo() != null ? scheduleCase.getScheduleInfo() : "");
                stateBuilder.append(scheduleCase.getScheduleState() != null ? scheduleCase.getScheduleState() : "");
            }

            downloadVo.setScheduleTime(timeBuilder.toString());
            downloadVo.setScheduleInfo(infoBuilder.toString());
            downloadVo.setScheduleState(stateBuilder.toString());
        }

        List<CaseAndScheduleDownloadVo> exportList = Collections.singletonList(downloadVo);
        ExcelUtil<CaseAndScheduleDownloadVo> util = new ExcelUtil<>(CaseAndScheduleDownloadVo.class);
        util.exportExcel(response, exportList, "案件进度明细数据");
    }
}
